<template>
  <div class="coupon-management">
    <h1>优惠券管理</h1>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input v-model="searchKeyword" placeholder="搜索优惠券编码或ID" style="width: 200px; margin-right: 10px;"></el-input>
      <el-select v-model="filterStatus" placeholder="筛选状态" style="width: 150px; margin-right: 10px;">
        <el-option label="全部" value="all"></el-option>
        <el-option label="可用" value="active"></el-option>
        <el-option label="不可用" value="inactive"></el-option>
        <el-option label="已过期" value="expired"></el-option>
      </el-select>
      <el-button type="primary" @click="fetchCoupons">搜索</el-button>
    </div>

    <!-- 添加优惠券表单 -->
    <div class="add-coupon-form">
      <h2>{{ isEditing ? '编辑优惠券' : '添加新优惠券' }}</h2>
      <el-form ref="couponForm" :model="couponForm" label-width="120px">
        <el-form-item label="折扣类型" prop="discountType">
          <el-select v-model="couponForm.discountType" placeholder="请选择折扣类型" @change="validateDiscountValue">
            <el-option label="百分比" value="percentage"></el-option>
            <el-option label="固定金额" value="fixed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣值" prop="discountValue">
          <el-input v-model="couponForm.discountValue" :placeholder="couponForm.discountType === 'percentage' ? '请输入0-100之间的数值' : '请输入大于0的数值'" @input="validateDiscountValue"></el-input>
          <el-form-item__error v-if="discountValueError">{{ discountValueError }}</el-form-item__error>
        </el-form-item>
        <el-form-item label="最低订单金额">
          <el-input v-model="couponForm.minOrderAmount" placeholder="请输入最低订单金额"></el-input>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="couponForm.startDate" type="date" placeholder="选择开始日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="couponForm.endDate" type="date" placeholder="选择结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="couponForm.status" placeholder="请选择状态">
            <el-option label="可用" value="active"></el-option>
            <el-option label="不可用" value="inactive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isEditing">
          <el-input v-model="couponForm.couponId" disabled placeholder="优惠券ID"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="isEditing ? updateCoupon() : addCoupon()">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button v-if="isEditing" @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 优惠券列表 -->
    <div class="coupon-list">
      <h2>优惠券列表</h2>
      <el-alert v-if="loading" title="数据加载中..." type="info" :closable="false"></el-alert>
      <el-alert v-else-if="couponsList.length === 0" title="暂无优惠券数据" type="warning" :closable="false"></el-alert>
      <el-table v-else :data="couponsList" style="width: 100%">
        <el-table-column prop="couponId" label="优惠券ID" width="80"></el-table-column>
        <el-table-column prop="couponCode" label="优惠券编码" width="180"></el-table-column>
        <el-table-column prop="discountType" label="折扣类型" width="100">
          <template slot-scope="scope">
            {{ scope.row.discountType === 'percentage' ? '百分比' : '固定金额' }}
          </template>
        </el-table-column>
        <el-table-column prop="discountValue" label="折扣值" width="80"></el-table-column>
        <el-table-column prop="minOrderAmount" label="最低订单金额" width="100"></el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120"></el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                {{ scope.row.status === 'active' ? '可用' : '不可用' }}
              </el-tag>
              <el-tag v-if="isExpired(scope.row.endDate)" type="warning" size="small" style="margin-left: 5px;">已过期</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="editCoupon(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="lockCoupon(scope.row.couponId)">锁定</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-container" v-if="!loading && couponsList.length > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getCoupons, addCoupon, lockCouponRecord, updateCoupon } from '../api/couponsApi'

export default {
  name: 'CouponManagement',
  data() {
    return {
      couponForm: {
        couponId: '',
        discountType: '',
        discountValue: '',
        minOrderAmount: '',
        startDate: '',
        endDate: '',
        status: 'active'
      },
      couponsList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      searchKeyword: '',
      filterStatus: 'all',
      isEditing: false,
      discountValueError: ''
    }
  },
  mounted() {
    this.fetchCoupons()
  },
  methods: {
    fetchCoupons() {
      this.loading = true
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        couponCode: this.searchKeyword,
        status: this.filterStatus === 'all' ? '' : this.filterStatus
      }
      getCoupons(params)
        .then(response => {
          this.couponsList = response.data.records
          this.totalCount = response.data.total
        })
        .catch(error => {
          this.$message.error('获取优惠券列表失败')
          console.error('Failed to fetch coupons:', error)
        }).finally(() => {
          this.loading = false
        })
    },
    addCoupon() {
      if (!this.validateDiscountValue()) {
        return
      }
      this.$refs.couponForm.validate(valid => {
        if (valid) {
          addCoupon(this.couponForm)
            .then(() => {
              this.$message.success('添加优惠券成功')
              this.resetForm()
              this.fetchCoupons()
            })
            .catch(error => {
              this.$message.error('添加优惠券失败')
              console.error('Failed to add coupon:', error)
            })
        }
      })
    },
    resetForm() {
      this.$refs.couponForm.resetFields()
      this.discountValueError = ''
    },
    cancelEdit() {
      this.isEditing = false
      this.resetForm()
    },
    editCoupon(row) {
      this.isEditing = true
      // 深拷贝避免直接修改表格数据
      this.couponForm = {...row}
    },
    updateCoupon() {
      if (!this.validateDiscountValue()) {
        return
      }
      this.$refs.couponForm.validate(valid => {
        if (valid) {
          updateCoupon(this.couponForm)
            .then(() => {
              this.$message.success('更新优惠券成功')
              this.isEditing = false
              this.resetForm()
              this.fetchCoupons()
            })
            .catch(error => {
              this.$message.error('更新优惠券失败')
              console.error('Failed to update coupon:', error)
            })
        }
      })
    },
    validateDiscountValue() {
      if (!this.couponForm.discountValue) {
        this.discountValueError = '请输入折扣值'
        return false
      }
      const value = Number(this.couponForm.discountValue)
      if (isNaN(value)) {
        this.discountValueError = '请输入有效的数字'
        return false
      }
      if (this.couponForm.discountType === 'percentage') {
        if (value < 0 || value > 100) {
          this.discountValueError = '百分比折扣必须在0-100之间'
          return false
        }
      } else if (this.couponForm.discountType === 'fixed') {
        if (value <= 0) {
          this.discountValueError = '固定金额折扣必须大于0'
          return false
        }
      }
      this.discountValueError = ''
      return true
    },
    isExpired(endDate) {
      if (!endDate) return false
      const today = new Date()
      today.setHours(0, 0, 0, 0)
      const expiryDate = new Date(endDate)
      expiryDate.setHours(23, 59, 59, 999)
      return today > expiryDate
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchCoupons()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchCoupons()
    },
    lockCoupon(couponId) {
      this.$confirm('确定要锁定此优惠券吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        lockCouponRecord({
          couponId: couponId,
          orderNumber: 'ORD' + Date.now() // 生成临时订单号
        })
          .then(() => {
            this.$message.success('锁定优惠券成功')
            this.fetchCoupons()
          })
          .catch(error => {
            this.$message.error('锁定优惠券失败')
            console.error('Failed to lock coupon:', error)
          })
      }).catch(() => {
        this.$message.info('已取消锁定')
      })
    }
  }
}
</script>

<style scoped>
.coupon-management {
  padding: 20px;
}

.add-coupon-form {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.coupon-list {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.search-filter {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

h1 {
  margin-bottom: 20px;
  color: #333;
}

h2 {
  margin-bottom: 15px;
  color: #666;
}
</style>